package javapop.framework.parser;

import javapop.framework.ParseContext;
import javapop.framework.ParseError;
import javapop.framework.ParseInput;
import javapop.framework.ParseResult;
import javapop.framework.Parser;

public class Char extends Parser<Character> {
	private Character ch;
	protected String description;
	
	public Char(Character ch) {
		if(ch==null) {
			throw new IllegalArgumentException("Character must not be <null>");
		}
		this.ch = ch;
		StringBuffer buf = new StringBuffer();
		buf.append("'");
		buf.append(this.ch);
		buf.append("'");
		description = buf.toString();
	}
	
	@Override
	public String getDescription() {
		return description;
	}
	
	protected Char() {
		ch = null;
		description = null;
	}
	
	@Override
	public boolean isMemoized() {
		return true;
	}

	public boolean acceptChar(Character ch) {
		return this.ch.equals(ch);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public final ParseResult<Character> eval(ParseContext<?> ctx, ParseInput input) {
		Character ch = input.fetch();
		if(acceptChar(ch)) {
			input.next();
			ParseResult<Character> result = buildResult(ch);			
			return result;
		} else {
			ParseResult error = new ParseError("Expecting "+description);
			return (ParseResult<Character>) error;
		}
	}
	
	@Override
	public int hashCode() {
		return ch.hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj==null) return false;
		if(obj==this) return true;
		if(obj.getClass()!=this.getClass())
			return false;
		return ((Char) obj).ch.equals(ch);
	}

	
}
